package main

import (
	"log"
	"net"
	"strings"
)

func main() {
	tcpServer(":10086")
}

func tcpServer(port string) {

	listener, e := net.Listen("tcp", port)
	if e != nil {
		log.Println(e)
		return
	}
	defer listener.Close()
	log.Println("listen ing~~~~~~~~~")
	for {
		conn, e := listener.Accept()
		if e != nil {
			log.Println(e)
			return
		}
		go handlerCon(conn)
	}

}

func handlerCon(con net.Conn) {
	addr := con.RemoteAddr().String()
	log.Println(addr, "is connected ")
	defer log.Println(addr, "handle finished")
	for {
		conten := make([]byte, 1024)
		n, err := con.Read(conten)
		if err != nil {
			log.Println("reciver data err=", err)
			break
		}
		contenStr := string(conten[:n])
		log.Printf("%s reciver data=%s", addr, contenStr)

		if strings.Compare(strings.TrimRight(contenStr, "\r\n"), "exit") == 0 {
			log.Printf("now %s need exit", addr)
			con.Write([]byte("bye"))
			break
		} else {
			con.Write(conten[:n])
		}
	}

}
